import { ForwardRefRenderFunction, memo, forwardRef, useState, useEffect, useImperativeHandle } from 'react'
import { List, Space, Modal } from 'antd'
import './style.less'
import { FileTextOutlined, DownloadOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'

import { getFileList, deleteFileByIds } from '@/api/operationCenter/docMaintain'

import { hsHandleTableDateTime, message, usePage } from '@hs-admin/utils'

import { HsAdminPage } from '@hs-admin/base-components'

import { previewPdfUrl, downloadFileBlob, downloadFile } from '@/api/file'
import { handleButtonShow } from '@/utils/tools'

interface Props {
  id: string | number
  searchValue: string
}
const DocMaintainList: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref) => {
  const [list, setList] = useState<any[]>([])
  const [isModalOpen, setisModalOpen] = useState(false)
  const [documentUrl, setdocumentUrl] = useState<any>(null)

  // 根据目录id查询文档
  const getFileByIds = async () => {
    if (!props.id) return

    const params: any = {
      page: pagination.current,

      page_size: pagination.pageSize,

      file_prefix_id: props.id
    }
    if (props.searchValue) {
      params.keyword = props.searchValue
    }
    const res: any = await getFileList(params)
    setList(res.items)

    return res
  }

  const { pagination, initPage, resetPage } = usePage(getFileByIds)

  // 表单modal-文件下载

  function callDownload(item: any) {
    downloadFile({
      file_id: item.id
    })
  }

  //删除对应目录的文档
  function deleteFileById(e: any) {
    deleteFileByIds({ ids: [e.id] }).then((res: any) => {
      if (res) {
        message.success('操作成功')
        resetPage()
      }
    })
  }

  const viewPdf = (e: any) => {
    downloadFileBlob({
      file_id: e.id
    }).then((res: any) => {
      setisModalOpen(true)
      setdocumentUrl(previewPdfUrl(res))
    })
  }

  useImperativeHandle(
    ref,
    () => {
      return { initPage }
    },
    [initPage]
  )

  useEffect(() => initPage(), [props.id, props.searchValue])

  return (
    <div className="bottom">
      <List
        className="demo-loadmore-list"
        itemLayout="horizontal"
        dataSource={list}
        footer={<HsAdminPage {...pagination} />}
        renderItem={(item) => (
          <List.Item
            actions={[
              <span>{hsHandleTableDateTime(item.created_at)}</span>,
              <DownloadOutlined onClick={() => callDownload(item)} />,
              handleButtonShow('datashop.data_document.delete') && <DeleteOutlined onClick={() => deleteFileById(item)} />,
              <div>{item.name.indexOf('.pdf') != -1 && <EyeOutlined onClick={() => viewPdf(item)} />}</div>
            ]}>
            <Space>
              <FileTextOutlined />
              <div>{item.name}</div>
            </Space>
          </List.Item>
        )}
      />
      <Modal title={'文档上传'} open={isModalOpen} onCancel={() => setisModalOpen(false)} footer={null} width={1000}>
        <iframe style={{ width: '800px', height: '500px' }} src={documentUrl} title="查看pdf"></iframe>
      </Modal>
    </div>
  )
}
export default memo(forwardRef(DocMaintainList))
